package com.sofwin.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.sofwin.ex.MyBlockHandler;
import com.sofwin.pojo.User;
import com.sofwin.service.UserService;
import com.sofwin.service.impl.DetpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @packageName: com.sofwin.controller
 * @author: andyliu
 * @date: 2022/5/18 11:43
 * @email 115176513@qq.com
 * @description: TODO
 */
@RestController
@RequestMapping("/dept")
public class DetpController {
    @Autowired
    // 进行远程服务调用的模板
    private RestTemplate restTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private DetpServiceImpl detpService;
    // 为了控制异常数
    private int count;

    // 服务发现的客户端
    // 来实现多个节点的服务的手动负载均衡的调用
    @Autowired
    private DiscoveryClient discoveryClient;
    @GetMapping("/data")
    public User data(Integer deptId){
        return userService.sdfsdf(deptId,"sdfsdf");
    }
    @GetMapping("/info")
    public String info(Integer userId){
        //
        List<ServiceInstance> instances = discoveryClient.getInstances("provider01");
        Random random = new Random();
        int index = random.nextInt(instances.size());
        ServiceInstance serviceInstance = instances.get(index);
        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/info/"+userId;
        String userName = restTemplate.getForObject(url, String.class);
        return userName;
    }
    @GetMapping("/info1")
    @SentinelResource("info1")
    public String info1(Integer userId){
        return userService.userInfo(userId);
    }
    @GetMapping("/info2")
    @SentinelResource("info2")
    public String info2(Integer userId){
        return userService.userInfo(userId);
    }
    @GetMapping("/message1")
    @SentinelResource("message1")
    public String message1(String name,Integer age) throws InterruptedException {
        count++;
        if(count%3==0){
            throw new RuntimeException();
        }

        return detpService.message(name)+"age:"+age;
    }
    @GetMapping("/message2")
    @SentinelResource(value="message2",fallback = "messageFallBack",fallbackClass = MyBlockHandler.class)
    public String message2(String name,Integer age){
        int a=1/0;
        return detpService.message(name)+"age:"+age;
    }




}
